import 'package:flutter/services.dart';
import 'package:flutter_module/beans/data_layer_bean.dart';
import 'package:flutter_module/beans/element_bean.dart';
import 'package:flutter_module/beans/project_bean.dart';
import 'package:flutter_module/map/models/library_models.dart';

import 'dispatcher/ni_data_dispatcher_factory.dart';
import 'ni_data_method_channel_handler.dart';

/// 数据通信中心
class NIDataController {
  /// 通信
  late MethodChannel _dataChannel;

  late NIDataMethodChannelHandler _methodChannelHandler;

  NIDataController.withId(int id) {
    _init(id);
  }

  void _init(int id) {
    _dataChannel = MethodChannel('com.navinfo.collect/data_$id');
    _methodChannelHandler = NIDataMethodChannelHandler();
    _dataChannel.setMethodCallHandler(_handlerMethod);
  }

  /// 数据代理回调
  ///
  /// native -> flutter
  Future<dynamic> _handlerMethod(MethodCall call) async {
    return await _methodChannelHandler.handlerMethod(call);
  }
}

///数据图层管理相关操作
extension DataLayerExtension on NIDataController {
  ///创建图层
  Future<bool> createDataLayer(DataLayer layer) async {
    return await NIDataDispatcherFactory.instance.dataLayerDispatcher
        .createDataLayer(_dataChannel, layer);
  }

  ///获取全部图层列表
  Future<List<DataLayer>> queryDataLayerList() async {
    return await NIDataDispatcherFactory.instance.dataLayerDispatcher
        .queryDataLayerList(_dataChannel);
  }

  ///获取某个图层
  Future<DataLayer?> queryDataLayer(String layerId) async {
    return await NIDataDispatcherFactory.instance.dataLayerDispatcher
        .queryDataLayer(_dataChannel, layerId);
  }
}

///数据图层管理相关操作
extension DataElementManagerExtension on NIDataController {
  ///保存数据
  Future<String?> saveElementData(ElementBean elementBean) async {
    return await NIDataDispatcherFactory.instance.dataElementDispatcher
        .saveElementData(_dataChannel, elementBean);
  }

  Future<Map?> importHdPbfData(List<String?> fileList) async {
    return await NIDataDispatcherFactory.instance.dataElementDispatcher
        .importHDPbfData(_dataChannel, fileList);
  }

  ///捕捉数据
  ///[list]要捕捉的坐标点的外接矩形坐标
  ///[wkt]  捕捉范围的几何 wkt格式 POLYGON((),())
  Future<List<ElementBean>> snapDataList(String wkt) async {
    return await NIDataDispatcherFactory.instance.dataElementDispatcher
        .snapDataList(_dataChannel, wkt);
  }

  Future<DataLayer?> queryElementDeepInfo(String id, String layerId) async {
    return await NIDataDispatcherFactory.instance.dataElementDispatcher
        .queryElementDeepInfo(_dataChannel, id, layerId);
  }
}

extension ProjectExtension on NIDataController {
  ///保存项目
  Future<bool> saveProject(Project project) async {
    return await NIDataDispatcherFactory.instance.dataProjectDispatcher
        .saveProject(_dataChannel, project);
  }

  Future<List<Project>> queryDataProjectList() async {
    return await NIDataDispatcherFactory.instance.dataProjectDispatcher
        .getDataProjectList(_dataChannel);
  }
}
